package com.hjl.cn.controller;


import com.alibaba.fastjson.JSONObject;
import com.hjl.cn.config.wxconfig.WxConfig;
import com.hjl.cn.utils.*;
import com.hjl.cn.vo.UsersVo;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author jialin
 * @createTime 2020-09-15
 */
@Log4j
@Controller
@RequestMapping(value = "/wx")
public class WxController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private WxConfig wxConfig;

    //http://localhost:8082/wx/getCode/
    @GetMapping(value = "/getCode")
    public String getCode() {
        return "redirect:" + wxConfig.getCode();
    }

    @RequestMapping(value = "/callBack")
    public void callBack(String code) throws IOException {
        String tokenUrl = wxConfig.getAccessToken(code);
        String callBackStr = HttpClientUtils.doGet(tokenUrl);

        JSONObject jsonObject = JSONObject.parseObject(callBackStr);
        //获取access_token，7200秒过期
        String accessToken = jsonObject.getString("access_token");
        //获取openId
        String openId = jsonObject.getString("openid");
        //获取refreshToken，30天过期
        String refreshToken = jsonObject.getString("refresh_token");

        String userInfo_str = HttpClientUtils.doGet(wxConfig.getUserInfo(accessToken, openId));
        String wxToken = accessToken;
        redisUtils.set(wxToken, userInfo_str, 7200);
        JSONObject.parseObject(userInfo_str, UsersVo.class);
        System.out.println(userInfo_str);
    }

    @ResponseBody
    @PostMapping(value = "/createUrl")
    public ReturnResult createUrl(@RequestParam String url) throws Exception {
        String content = url;
        //String filePath = "/home/jialin/file/img/qrCode/qrCode.png";
        String filePath = "D://qrCode.png";
        try {
            QRCodeUtil.createQrCode(new FileOutputStream(new File(filePath)), content, 900, "png");
            return ReturnResultUtils.returnSuccess("创建二维码图片成功！");
        } catch (Exception e) {
            log.error("创建二维码图片失败！");
            return ReturnResultUtils.returnFailMsg(612, "创建二维码图片失败！");
        }
    }
    
    public void timeToBuy(){
        boolean isLock = false;
        while (true){
            if (!isLock){
                break;
            }
        }
        // TODO: 2020/9/16  
    }

}
